#include <mpx_supt.h>

void help() {
	char *a="Help Page\n\n\0"; //9
	 char *b="Command -> Description\n\0"; //22
	 char *c="exit -> exits MPX\n\0"; //16
	char *d="display-date -> displays the current system date\n\0"; //58
	 char *e="set-date MMDDYYYY -> sets the system date with the specified format\n\0"; //75
  char *f="dir <directory name> -> shows all the .MPX files in a directory\n\0"; //70
	sys_req(2,1,a,10);
  sys_req(2,1,b,25);
  sys_req(2,1,c,20);
  sys_req(2,1,d,60);
  sys_req(2,1,e,80);
  sys_req(2,1,f,75);
}

void displayDate() {
  char *date=sys_alloc_mem(10*sizeof(char));
	date_rec *d=sys_alloc_mem(sizeof(date_rec));
	sys_get_date(d);
	strcpy(date,d.month);
	strcat(date,"/");
	strcat(date,d.day);
	strcat(date,"/");
	strcat(date,d.year);
	sys_req(2,1,date,10);
}

void setDate(char *date) {
	if(date==NULL) {
		sys_req(2,1,"missing argument\n\0", 16);
	}
	else {
		date_rec *d=sys_alloc_mem(sizeof(date_rec));
		d.month=10*date[0]+date[1];
		d.day=10*date[2]+date[3];
		d.year=1000*date[4]+100*date[5]+10*date[6]+date[7];
		sys_set_date(d);
		displayDate();
	}
}

void getEntries() {
	char *ent=sys_alloc_mem(20*sizeof(char));
	long *size;
	int err=sys_get_entry(ent,20,size);
	sys_req(2,1,"Filename             Size\n\0", 30);
	while(err==0) {
		char *file=sys_alloc_mem((22*sizeof(char))+sizeof(long));
		strcpy(file,ent);
		strcat(file,"\t");
		strcat(file,size);
		sys_req(2,1,file,30);
		err=sys_get_entry(ent,20,size);
	}
}

void analyzeInput(char *in) {
	char *h="help\0";
	char *e="exit\0";
	char *d="display-date\0";
	char *s="set-date\0";
	char *dir="dir\0";
	char *version="version\0";
	if(strcmp(in,h)==0)
		help();
	else if(strcmp(in,e)==0)
		sys_exit();
	else if(strcmp(in,d)==0)
		displayDate();
	else if(strncmp(in,s,8)==0) {
		char *newD=sys_alloc_mem(8*sizeof(char));
		int i=8;
		int n=0;
		while(in[i]!=NULL) {
			if(!isspace(in[i])) {
				if(isDigit(in[i])) {
					newD[n]=in[i];
					n++;
				}
			}
			i++;
		}
		if(n==9)
			setDate(newD);
		else
			sys_req(2,1,"incorrect date format\n\0", 25);
	}
	else if(strcmp(in,dir)==0) {
		char *directory=sys_alloc_mem(20*sizeof(char));
		int i=3;
    int j=0;
    int err=0;
		while(isspace(in[i])) {
			i++;
		}
		while(in[i]!=NULL) {
			directory[j]=in[i];
			i++;
			j++;
		}
		err=sys_open_dir(directory);
		if(err==0) {
      sys_open_dir(directory);
			getEntries();
    }
		else
			sys_req(2,1,"directory doesn't exist\n\0", 25);
	}
	else if(strcmp(in,version)==0) {
		sys_req(2,1,"R1\0",2);
	}
}

void getInput() {

	char *in=sys_alloc_mem(50*sizeof(char));
	while(1) {
		sys_req(2,1,">",1);
		sys_req(1,1,in,50);
		analyzeInput(in);
		sys_req(2,1,"\n",0);
	}
}

int main() {
	
	sys_init(1);
	getInput();
  return 0;
}
 
